//
//  CNBBSContentViewController.m
//  CsdnPlus
//
//  Created by 孟瑞瑞 on 2018/5/29.
//  Copyright © 2018年 CSDN. All rights reserved.
//

#import "CNBBSContentViewController.h"
#import "CNBBSListCell.h"
#import "CNBBSListViewModel.h"
#import "CNBBSDetailViewController.h"
#import <CNBaseViewTool/CNLoadingGifView.h>
#import <CNBaseViewTool/CNNoDataView.h>
#import <Masonry/Masonry.h>
#import <CNBaseTool/CNCategoryHeader.h>
#import <CNBaseViewTool/CNNoDataView.h>
#import <CNBaseViewTool/UIView+CNEmpty.h>
#import <CNBaseViewTool/CNRefreshGifHeader.h>
#import <CNBaseViewTool/CNRefreshAutoNormalFooter.h>
#import <CNBaseViewTool/CNViewConst.h>


@interface CNBBSContentViewController () <UITableViewDelegate,UITableViewDataSource,CNBBSListCellDelegate>
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) CNBBSListViewModel *bbsVM;

@property (nonatomic, strong) CNLoadingGifView *loadingView;

@property (nonatomic, strong) CNNoDataView *noDataView;

@property (nonatomic, strong) CNNoDataView *noNetworkView;

@end

@implementation CNBBSContentViewController

-(CNBBSListViewModel *)bbsVM
{
    if (!_bbsVM) {
        _bbsVM = [[CNBBSListViewModel alloc]init];
    }
    return _bbsVM;
}

- (CNLoadingGifView *)loadingView{
    if(!_loadingView){
        _loadingView = [[CNLoadingGifView alloc]init];
        [self.view addSubview:_loadingView];
        [_loadingView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(0);
        }];
    }
    return _loadingView;
}

- (CNNoDataView *)noDataView{
    if (!_noDataView) {
        _noDataView = [CNNoDataView diyEmptyView];
    }
    if ([CNThemesManager isNight])
    {
        _noDataView.imageStr = @"noData_b";
    }
    else
    {
        _noDataView.imageStr = @"noData_w";
    }
    return _noDataView;
}
- (CNNoDataView *)noNetworkView{
    if (!_noNetworkView) {
        _noNetworkView = [CNNoDataView diyEmptyActionViewWithTarget:self action:@selector(headerRefresh)];
    }
    if ([CNThemesManager isNight])
    {
        _noNetworkView.imageStr = @"noNetwork_b";
    }
    else
    {
        _noNetworkView.imageStr = @"noNetwork_w";
    }
    return _noNetworkView;
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView=[[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = YES;
        _tableView.theme_backgroundColor = searchPageBGColorPicker;
        _tableView.tableFooterView = [UIView new];
        _tableView.estimatedRowHeight = 124;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        [_tableView registerClass:[CNBBSListCell class] forCellReuseIdentifier:@"bbsListCell"];
        [self.view addSubview:_tableView];
        
        if (DEVICE_IS_IPHONE4 || DEVICE_IS_IPHONE5) {
            [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(0);
                make.left.right.bottom.mas_equalTo(0);
            }];
            
        }
        else
        {
            [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(0);
                make.left.right.bottom.mas_equalTo(0);
            }];
            
        }
        //        _tableView.contentInset = UIEdgeInsetsMake(0, 0, 64, 0);
        
        //去掉分割线
        _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
        
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            // Fallback on earlier versions
        };
        
        @weakify(self);
        _tableView.mj_header = [CNRefreshGifHeader headerWithRefreshingBlock:^{
            @strongify(self);
            [self refreshData:YES shouldShowTips:YES];
        }];
        _tableView.autoHideMjFooter = YES;
        _tableView.mj_footer = [CNRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            @strongify(self);
            [self refreshData:NO shouldShowTips:NO];
        }];
        _tableView.cn_emptyView = self.noDataView;
        
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.view.theme_backgroundColor = searchPageBGColorPicker;
    //[self refreshData];
    self.tableView.hidden = NO;
    [self refreshData:YES shouldShowTips:YES];
    //[self.tableView.mj_header beginRefreshing];
    //监听更换皮肤通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeSkin) name:CNThemeUpdateNotification object:nil];
    
    //添加分割线
//    UIView *lineView = [[UIView alloc]init];
//    lineView.theme_backgroundColor = bbsSectionLineColorPicker;
//    [self.view addSubview:lineView];
//    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.right.mas_equalTo(0);
//        make.top.mas_equalTo(0);
//        make.height.mas_equalTo(0.5);
//    }];
//    lineView.layer.zPosition = 10;
}

- (void)changeSkin
{
    [self.tableView reloadData];
}


#pragma mark -- 刷新数据

- (void)refreshData:(BOOL)header shouldShowTips:(BOOL)showTip
{
    
    if (header)
    {
        [self.loadingView setHidden:self.bbsVM.rowNumber];
        //占位图调用时机
        [self.tableView cn_startLoading];
        [self.bbsVM refreshBBSListDataWithTocipType:self.topiceType CompletionHandle:^(NSError *error) {
            if (!error)
            {
                if (self.bbsVM.code == 200)
                {
                    //AF的回调 是在主线程中
                    [self.tableView reloadData];
                    [self.loadingView setHidden:YES];
                    self.tableView.cn_emptyView = self.noDataView;
                }
                else
                {
                    [self.loadingView setHidden:YES];
                    [self showErrorMsg:@"加载失败，请稍后再试"];
                    
                }
                //   重置脚步 没有更多数据
                [self.tableView.mj_footer resetNoMoreData];
                
            }else
            {
                [self showError:error];;
                [self.loadingView setHidden:YES];
                self.tableView.cn_emptyView = self.noNetworkView;
               
            }
            [self.tableView.mj_header endRefreshing];
            //占位图调用时机
            [self.tableView cn_endLoading];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"hideLoading" object:nil];
        }];
    }
    else
    {
        //占位图调用时机
        [self.tableView cn_startLoading];
        [self.bbsVM getMoreBBSListDataWithTocipType:self.topiceType CompletionHandle:^(NSError *error) {
            
            if (!error)
            {
                if (self.bbsVM.code == 200)
                {
                    //AF的回调 是在主线程中
                    [self.tableView reloadData];
                    self.tableView.cn_emptyView = self.noDataView;
                }
                else
                {
                    [self showErrorMsg:@"加载失败，请稍后再试"];
                }
                if ([self.bbsVM isHasMore])
                {
                    [self.tableView.mj_footer endRefreshing];
                }
                else
                {
                    [self.tableView.mj_footer endRefreshingWithNoMoreData];
                }
            }
            else
            {
                [self showError:error];;
                [self.tableView.mj_footer endRefreshing];
                self.tableView.cn_emptyView = self.noNetworkView;
            }
            //占位图调用时机
            [self.tableView cn_endLoading];
        }];
    }
    
}

#pragma mark - Public Method
/** 暴露给外边的刷新方法 */
- (void)headerRefresh {
    [self.tableView.mj_header beginRefreshing];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.bbsVM.rowNumber;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CNBBSListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"bbsListCell" forIndexPath:indexPath];
    
    if (indexPath.row < self.bbsVM.rowNumber)
    {
        //配置Cell
        [self configureCell:cell atIndexPath:indexPath];
    }
    
    return cell;
}


- (void)configureCell:(CNBBSListCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    //    cell.fd_enforceFrameLayout = NO; // Enable to use "-sizeThatFits:"
    cell.delegate = self;
    
    cell.forumLb.text = [NSString stringWithFormat:@"%@",[self.bbsVM forumForRow:indexPath.row]];
    
    if (self.isTech)
    {
        cell.forumLb.theme_textColor = techTextColorPicker;
    }
    else
    {
        cell.forumLb.theme_textColor = nonTechTextColorPicker;
    }
    
    NSString *titleText = [NSString stringWithFormat:@"%@",[self.bbsVM titleForRow:indexPath.row] ?:@""];
    
    NSMutableAttributedString  *setStringtitle = [[NSMutableAttributedString alloc] initWithString:titleText];
    setStringtitle.yy_lineSpacing = 2;
    setStringtitle.yy_font = [UIFont boldSystemFontOfSize:17];
    if ([CNThemesManager isNight])
    {
        setStringtitle.yy_color = navigationBarNightTitleColor;
    }
    else
    {
        setStringtitle.yy_color = navigationBarTitleColor;
    }
   
    //可以将要插入的图片作为特殊字符处理
    //需要使用 YYAnimatedImageView 控件，直接使用UIImage添加无效。
    
    YYAnimatedImageView *imageView1= [[YYAnimatedImageView alloc] initWithImage:[UIImage imageNamed:@"jing"]];
    imageView1.frame = CGRectMake(0, 0, 20, 20);
    
    YYAnimatedImageView *imageView2= [[YYAnimatedImageView alloc] initWithImage:[UIImage imageNamed:@"ding"]];
    imageView2.frame = CGRectMake(0, 0, 20, 20);
    // attchmentSize 修改，可以处理内边距
    NSMutableAttributedString *attachText1= [NSMutableAttributedString yy_attachmentStringWithContent:imageView1 contentMode:UIViewContentModeScaleAspectFit attachmentSize:imageView1.frame.size alignToFont:[UIFont systemFontOfSize:17] alignment:YYTextVerticalAlignmentCenter];
    attachText1.yy_lineSpacing = 2;
    NSMutableAttributedString *attachText2= [NSMutableAttributedString yy_attachmentStringWithContent:imageView2 contentMode:UIViewContentModeScaleAspectFit attachmentSize:imageView2.frame.size alignToFont:[UIFont systemFontOfSize:17] alignment:YYTextVerticalAlignmentCenter];
    attachText2.yy_lineSpacing = 2;
    NSMutableAttributedString  *attachText3 = [[NSMutableAttributedString alloc] initWithString:@" "];
    attachText3.yy_lineSpacing = 2;
    
    if ([self.bbsVM isRecommendForRow:indexPath.row] && [self.bbsVM isTopForRow:indexPath.row])
    {
        [setStringtitle insertAttributedString:attachText1 atIndex:0];
        [setStringtitle insertAttributedString:attachText3 atIndex:1];
        [setStringtitle insertAttributedString:attachText2 atIndex:2];
        [setStringtitle insertAttributedString:attachText3 atIndex:3];
    }
    else if ([self.bbsVM isRecommendForRow:indexPath.row])
    {
        [setStringtitle insertAttributedString:attachText1 atIndex:0];
        [setStringtitle insertAttributedString:attachText3 atIndex:1];
    }
    else if ([self.bbsVM isTopForRow:indexPath.row])
    {
        [setStringtitle insertAttributedString:attachText2 atIndex:0];
        [setStringtitle insertAttributedString:attachText3 atIndex:1];
    }
   
    
    // 设置Label要显示的text
    [cell.titleLb  setAttributedText:setStringtitle];
    NSString *descText = [self.bbsVM introductionForRow:indexPath.row] ?:@"";
    
    UIColor *color = [UIColor whiteColor];
    if ([CNThemesManager isNight])
    {
        color = cellDesNightTitleTextColor;
    }
    else
    {
        color = cellDesTitleTextColor;
    }
    NSMutableAttributedString  *setDesString = [CNViewConst processCommentContent:[PPStickerDataManager changeEmojiHPurlWithEmojiDesc:descText] Fount:[UIFont systemFontOfSize:14] Color:color LineSpacing:2.0];
    if ([CNThemesManager isNight])
    {
        setDesString.yy_color = cellDesNightTitleTextColor;
    }
    else
    {
        setDesString.yy_color = cellDesTitleTextColor;
    }
    setDesString.yy_lineSpacing = 2;
    setDesString.yy_font = [UIFont systemFontOfSize:14];
    if ([CNThemesManager isNight])
    {
        setDesString.yy_color = cellDesNightTitleTextColor;
    }
    else
    {
        setDesString.yy_color = cellDesTitleTextColor;
    }
    // 设置Label要显示的text
    [cell.descriptionLb  setAttributedText:setDesString];
    cell.descriptionLb.lineBreakMode = NSLineBreakByTruncatingTail;//label的换行模式
    @weakify(cell);
    [cell.headImageBtn yy_setBackgroundImageWithURL:[self.bbsVM avatarForRow:indexPath.row] forState:(UIControlStateNormal) placeholder:[UIImage imageNamed:@"headImage"] options:kNilOptions progress:nil transform:nil completion:^(UIImage * _Nullable image, NSURL * _Nonnull url, YYWebImageFromType from, YYWebImageStage stage, NSError * _Nullable error) {
        @strongify(cell);
        if (!error) {
            image = [UIImage imageWithRoundCorner:image cornerRadius:16 size:CGSizeMake(32, 32)];
            [cell.headImageBtn setBackgroundImage:image forState:(UIControlStateNormal)];
        }
    }];
    
    
    cell.fromLb.text = [self.bbsVM nicknameForRow:indexPath.row];
    
    cell.timeLb.text = [self.bbsVM createdAtForRow:indexPath.row];
    
    //cell.commentImageView.image = [UIImage imageNamed:@"blogComment"];
    
    cell.commentLb.text = [NSString stringWithFormat:@"%@%@",@"帖子",[[self.bbsVM postCountForRow:indexPath.row] isEqualToString:@"0"] ?@"":[self.bbsVM postCountForRow:indexPath.row]];
    
    cell.scoreLb.text = [NSString stringWithFormat:@"%@分",[self.bbsVM scoreForRow:indexPath.row]];
    
    cell.lineView.hidden = NO;
    
}

#pragma mark - CNBBSListCellDelegate

-(void)cellDidClickHeadImage:(CNBBSListCell *)cell
{
//    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
//    CNHisViewController *hisVC = [[CNHisViewController alloc]initWithUserName:[self.bbsVM usernameForRow:indexPath.row]];
//    [self.navigationController pushViewController:hisVC animated:YES];
    
}


#pragma mark - UITableViewDelegate

//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    return [tableView fd_heightForCellWithIdentifier:@"resultCell" cacheByIndexPath:indexPath configuration:^(CNSearchResultCell *cell) {
//        [self configureCell:cell atIndexPath:indexPath];
//    }];
//}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    CNBBSDetailViewController *vc = [[CNBBSDetailViewController alloc]init];
    vc.bbsTitle = [NSString stringWithFormat:@"%@",[self.bbsVM titleForRow:indexPath.row]];
    vc.topicId = [self.bbsVM IdForRow:indexPath.row];
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)dealloc
{
    //在页面消失的回调方法中移除通知。
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
